﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AiXiu.WebSite
{
    public partial class PersonalEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //第一次加载页面
            if (!IsPostBack)
            {
                // 读取用户资料
                TBUsers user = IdentityManager.ReadUser();

                //显示用户信息
                txtNickName.Text = user.NickName;
                ddlSex.SelectedIndex = (int)user.Sex;
                txtBirthday.Text = user.Birthday.HasValue ? user.Birthday.Value.ToString("yyyy-MM-dd") : "";
                hidAddress.Value = user.Address;
                hidHobby.Value = user.Hobby;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            // 读取信息
            TBUsers user = IdentityManager.ReadUser();
            user.NickName = this.txtNickName.Text;
            user.Sex = this.ddlSex.SelectedIndex;
            if (!string.IsNullOrEmpty(this.txtBirthday.Text))
            {
                user.Birthday = DateTime.Parse(this.txtBirthday.Text);
            }
            user.Address = hidAddress.Value;
            user.Hobby = hidHobby.Value;
            // 更新资料
            UsersBLL userManager = new UsersBLL();
            OperResult<TBUsers> editResult = userManager.EditWithoutAvatar(user);
            if (editResult.StatusCode == StatusCode.Succeed)
            {
                TBUsers userEntity = editResult.ReadResult();
                // 读取缓存用户资料
                TBUsers userCookie = IdentityManager.ReadUser();
                if (userCookie == null)
                {
                    this.Alert("cookienull", "缓存读取出错！");
                }
                // 更新用户资料
                userCookie.NickName = userEntity.NickName;
                userCookie.Sex = userEntity.Sex;
                userCookie.Birthday = userEntity.Birthday;
                userCookie.Address = userEntity.Address;
                userCookie.Hobby = userEntity.Hobby;
                // 缓存用户资料
                IdentityManager.SaveUser(userCookie);
                // 跳转到个人页
                Response.Redirect("Personal.aspx");
            }
            else
            {
                this.Alert("editerror", editResult.Message);
            }
        }
    }
}